/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.account.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.entity.SysUser;
import com.rzico.core.plugin.PaymentPlugin;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysPluginService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.Filter;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.account.entity.Payment;
import com.rzico.account.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 收款单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "收款单接口")
@RestController
@RequestMapping("/payment")
public class PaymentController extends BaseController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private SysPluginService sysPluginService;

    @Autowired
    private EnterpriseService enterpriseService;


    @Autowired
    private SysMchService sysMchService;

    /**
     *  支付通知
     *
     * @param paymentPluginId
     * @return
     */
    @Log(desc = "支付通知", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("支付通知")
    @PostMapping("/notify/{paymentPluginId}/{mchId}")
    public void notify(@PathVariable String paymentPluginId,@PathVariable String mchId,HttpServletRequest request,HttpServletResponse response) {

        PaymentPlugin paymentPlugin = sysPluginService.getPaymentPlugin(paymentPluginId);

        SysPlugin sysPlugin = sysPluginService.findByPlugin(mchId,paymentPluginId);

        Map<String,Object> resultMap = paymentPlugin.verifyNotify(sysPlugin,request);

        String notifyMessage = "error";
        if ("0000".equals(resultMap.get("return_code").toString())) {
            //此处改为MQ通知异步执行

            String sn = resultMap.get("tradeNo").toString();
            try {
                paymentService.handle(sn,resultMap.get("tranSn").toString());
                notifyMessage = paymentPlugin.getNotifyMessage(request);
            } catch (Exception e) {
                notifyMessage = "error";
            }

        }
        try {
            PrintWriter out = response.getWriter();
            out.print(paymentPlugin.getNotifyMessage(request));
            out.flush();
        } catch (IOException e) {

        }

    }

    /**
     *  状态查询
     *
     * @param sn
     * @return
     */
    @Log(desc = "状态查询", type = Log.LOG_TYPE.SELECT)
    @ApiOperation("状态查询")
    @GetMapping("/query")

    public CommResult<Payment> query(String sn,HttpServletRequest request) {

        Payment payment = paymentService.findBySn(sn);

        PaymentPlugin paymentPlugin = sysPluginService.getPaymentPlugin(payment.getPaymentPluginId());

        Enterprise enterprise = enterpriseService.findById(payment.getEnterpriseId());

        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        if (sysMch.getMchType().equals(2)) {
            //特约商户,服务商代收
            enterprise = enterpriseService.findByMch(sysMch.getIsvId());
        }

        SysPlugin sysPlugin = sysPluginService.findByPlugin(enterprise.getMchId(),payment.getPaymentPluginId());
        if (sysPlugin==null) {
            return CommResult.error("无效插件编号");
        }

        Map<String,Object> resultMap = paymentPlugin.tradeQuery(sysPlugin,payment.getSn(),payment.getTranSn(),request);

        if ("0000".equals(resultMap.get("return_code").toString())) {
            try {
                paymentService.handle(sn,resultMap.get("tranSn").toString());
                return CommResult.success(resultMap);
            } catch (Exception e) {
                return CommResult.error("通知失败");
            }
        } else if ("0001".equals(resultMap.get("return_code").toString())) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return query(sn,request);
        } else {
            return CommResult.success(resultMap);
        }

    }

    /**
     * 查询单条收款单
     *
     * @return
     */
    @ApiOperation("查询单条收款单")
    @GetMapping("/find/{sn}")
    public CommResult<Payment> find(@PathVariable String sn) {
        Payment result = paymentService.findBySn(sn);

        Map<String,Object> data = new HashMap<>();
        data.put("payment",result);
        return CommResult.success(data);

    }

}
